/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.tools;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.oslef.model.History;
import org.oslef.model.LoanModel;
import org.oslef.model.Translator;
import org.oslef.tools.db.DbLoan;


public final class Fingerprint {

	public int loanCount = 0;
	public BigDecimal totalProceeds = BigDecimal.ZERO;
	public final Map<String, BigDecimal> totalFinancedFees = new HashMap<String, BigDecimal>();
	public final Map<String, BigDecimal> totalBalances = new HashMap<String, BigDecimal>();
	
	public void update(DbLoan s) {
		
		LoanModel loan = Translator.parse(s, null);
		
		loanCount++;
		totalProceeds = totalProceeds.add(loan.struct.loanAmount);
		
		for (String name : loan.struct.financedFees.keySet()) {
			BigDecimal value = loan.struct.financedFees.get(name);
			BigDecimal total = totalFinancedFees.get(name);
			if (total == null) total = BigDecimal.ZERO;
			total = total.add(value);
			totalFinancedFees.put(name, total);
		}
		
		for (History h : loan.history) {
			for (String name : h.accounts.keySet()) {
				BigDecimal value = h.accounts.get(name);
				BigDecimal total = totalBalances.get(name);
				if (total == null) total = BigDecimal.ZERO;
				total = total.add(value);
				totalBalances.put(name, total);
			}
		}
	}
	
	private static ObjectWriter w;
	{
		ObjectMapper m = new ObjectMapper();
		w = m.defaultPrettyPrintingWriter();
	}
	
	@Override
	public String toString() {
		try { return w.writeValueAsString(this); } 
		catch (Exception ex) { throw new RuntimeException(ex); }
	}
}
